package com.example.showlocation;

import static androidx.core.content.PermissionChecker.PERMISSION_DENIED;
import static androidx.core.content.PermissionChecker.PERMISSION_DENIED_APP_OP;
import static androidx.core.content.PermissionChecker.PERMISSION_GRANTED;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.location.Location;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.PermissionChecker;

import com.tencent.map.geolocation.TencentLocation;
import com.tencent.map.geolocation.TencentLocationListener;
import com.tencent.map.geolocation.TencentLocationManager;
import com.tencent.map.geolocation.TencentLocationRequest;
import com.tencent.tencentmap.mapsdk.maps.LocationSource;
import com.tencent.tencentmap.mapsdk.maps.TencentMap;
import com.tencent.tencentmap.mapsdk.maps.TencentMapInitializer;
import com.tencent.tencentmap.mapsdk.maps.TextureMapView;
import com.tencent.tencentmap.mapsdk.maps.model.BitmapDescriptor;
import com.tencent.tencentmap.mapsdk.maps.model.BitmapDescriptorFactory;
import com.tencent.tencentmap.mapsdk.maps.model.LatLng;
import com.tencent.tencentmap.mapsdk.maps.model.MyLocationStyle;
import com.tencent.tencentmap.mapsdk.maps.model.Polyline;
import com.tencent.tencentmap.mapsdk.maps.model.PolylineOptions;

import java.util.ArrayList;
import java.util.List;

public class ShowMyLocationActivity extends AppCompatActivity implements LocationSource {
    TencentLocationManager locationManager;
    TencentLocationRequest locationRequest;
    MyLocationListener mLocationListener;
    OnLocationChangedListener onLocationChangedListener;
    TextureMapView textureMapView;
    TencentMap mTencentMap;
    Location location ;
    ActivityResultLauncher<String> requestPermissionLauncher;
    List<LatLng> latLngs;
    List<LatLng> listPoints ;
    Polyline polyline;
    int i=0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        TencentMapInitializer.setAgreePrivacy(true);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_my_location);
        textureMapView=(TextureMapView)findViewById(R.id.view4) ;
        mTencentMap = textureMapView.getMap();
        location = new Location("LongPressLocationProvider");
        locationManager = TencentLocationManager.getInstance(this);
        //创建定位请求
        locationRequest = TencentLocationRequest.create();
        locationRequest.setGpsFirst(true);
        locationRequest.setInterval(3000);
        mTencentMap.setMyLocationClickListener(new TencentMap.OnMyLocationClickListener() {
            @Override
            public boolean onMyLocationClicked(LatLng latLng) {
                Toast.makeText(ShowMyLocationActivity.this, "内置定位标点击回调", Toast.LENGTH_SHORT).show();
                return true;
            }
        });
        requestPermissionLauncher =
                registerForActivityResult(new ActivityResultContracts.RequestPermission(), isGranted -> {
                    if (isGranted) {
                        requestLocationUpdates();
                        Log.d(getLocalClassName()+":","isGranted" );
                        // Permission is granted. Continue the action or workflow in your
                        // app.
                    } else {
                        Log.d(getLocalClassName()+":","else" );
                        //requestPermissionLauncher.launch("android.permission.ACCESS_FINE_LOCATION");
                        // Explain to the user that the feature is unavailable because the
                        // feature requires a permission that the user has denied. At the
                        // same time, respect the user's decision. Don't link to system
                        // settings in an effort to convince the user to change their
                        // decision.
                    }
                });
        latLngs = new ArrayList<LatLng>();

    }
    void requestLocationUpdates(){
        mLocationListener=new  MyLocationListener();
        TencentLocationManager.setUserAgreePrivacy(true);
        int err = locationManager.requestLocationUpdates(
                locationRequest,mLocationListener , Looper.myLooper());
        //int err =locationManager.requestSingleFreshLocation(locationRequest,mLocationListener,Looper.myLooper());
        switch (err) {
            case 1:
                Toast.makeText(this,
                        "设备缺少使用腾讯定位服务需要的基本条件",
                        Toast.LENGTH_SHORT).show();
                break;
            case 2:
                Toast.makeText(this,
                        "manifest 中配置的 key 不正确", Toast.LENGTH_SHORT).show();
                break;
            case 3:
                Toast.makeText(this,
                        "自动加载libtencentloc.so失败", Toast.LENGTH_SHORT).show();
                break;
            default:
                break;
        }}
    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        this.onLocationChangedListener=onLocationChangedListener;
        int  isGranted=PermissionChecker.checkCallingPermission(this,"android.permission.ACCESS_FINE_LOCATION","com.example.showmylocation");
        switch (isGranted){
            case PERMISSION_GRANTED:
                requestLocationUpdates();
                break;
            case  PERMISSION_DENIED:
                    requestPermissionLauncher.launch("android.permission.ACCESS_FINE_LOCATION");
                    Log.d(getLocalClassName()+":", "case  PERMISSION_DENIED");
                break;
            case  PERMISSION_DENIED_APP_OP:
                break;
        }

        Log.d(getLocalClassName()+":", "activate");
    }
    @Override
    public void deactivate() {
        Log.d(getLocalClassName()+":", "deactivate");
    }

    class MyLocationListener implements TencentLocationListener {

        @Override
        public void onLocationChanged(TencentLocation tencentLocation, int error, String reason) {

            //其中 locationChangeListener 为 LocationSource.active 返回给用户的位置监听器
            //用户通过这个监听器就可以设置地图的定位点位置
            if(error == TencentLocation.ERROR_OK && onLocationChangedListener != null){
                //设置经纬度
                location.setLatitude(tencentLocation.getLatitude());
                location.setLongitude(tencentLocation.getLongitude());
                //设置精度，这个值会被设置为定位点上表示精度的圆形半径
                location.setAccuracy(tencentLocation.getAccuracy());
                //设置定位标的旋转角度，注意 tencentLocation.getBearing() 只有在 gps 时才有可能获取
                //location.setBearing((float) tencentLocation.getBearing());
                //设置定位标的旋转角度，注意 tencentLocation.getDirection() 返回的方向，仅来自传感器方向，如果是gps，则直接获取gps方向
                location.setBearing((float) tencentLocation.getDirection());
                //将位置信息返回给地图
                onLocationChangedListener.onLocationChanged(location);
            }
            /*if (i<=1) {
                latLngs.add(new LatLng(tencentLocation.getLatitude(),tencentLocation.getLongitude()));
                if (i == 1) {
                    polyline = mTencentMap.addPolyline(new PolylineOptions().addAll(latLngs).color(0xff00ff00));
                    Log.d(getLocalClassName()+":", String.valueOf(polyline.getPoints().size()));
                }


                i++;
            }
            else{
                listPoints = new ArrayList<LatLng>();
                listPoints.add(new LatLng(tencentLocation.getLatitude(),tencentLocation.getLongitude()));
                polyline.appendPoints(listPoints );

                i++;
                Log.d(getLocalClassName()+":", String.valueOf(polyline.getPoints().size()));
            }*/
            if (i==0) {
                latLngs.add(new LatLng(tencentLocation.getLatitude(),tencentLocation.getLongitude()));

                    polyline = mTencentMap.addPolyline(new PolylineOptions().addAll(latLngs).color(0xff00ff00));
                    Log.d(getLocalClassName()+":", String.valueOf(polyline.getPoints().size()));



                i++;
            }
            else{
                listPoints = new ArrayList<LatLng>();
                listPoints.add(new LatLng(tencentLocation.getLatitude(),tencentLocation.getLongitude()));
                polyline.appendPoints(listPoints );

                i++;
                Log.d(getLocalClassName()+":", String.valueOf(polyline.getPoints().size()));
            }


            Log.d(getLocalClassName()+":", location.getLatitude()+","+location.getLongitude());
            Log.d(getLocalClassName()+":", "onLocationChanged");
        }

        @Override
        public void onStatusUpdate(String name, int status, String desc) {
            /**
             * name - 设备名, GPS, WIFI, CELL 中的某个
             * status - 状态码, STATUS_ENABLED, STATUS_DISABLED, STATUS_UNKNOWN, STATUS_GPS_AVAILABLE, STATUS_GPS_UNAVAILABLE, STATUS_DENIED中的某个 在使用status之前,请先按照name进行区分
             * desc - 状态描述
             */
        }
    }
    @SuppressLint("IntentReset")
    public void ShowMyLocation(View view) throws Exception {
        mTencentMap.setLocationSource(this);
        mTencentMap.setMyLocationEnabled(true);
        MyLocationStyle myLocationStyle=new MyLocationStyle();
        BitmapDescriptor custom = BitmapDescriptorFactory.fromResource(R.drawable.icon);
        //myLocationStyle.icon(custom);
            myLocationStyle.strokeColor(Color.parseColor("#AF5D5D"));
        myLocationStyle.strokeWidth(30);
        //myLocationStyle.myLocationType(LOCATION_TYPE_LOCATION_ROTATE_NO_CENTER);
        mTencentMap.setMyLocationStyle(myLocationStyle);
        Log.d(getLocalClassName()+":", "ShowMyLocation(View view)");
    }
    void addPolyline_appendPoints(Double latitude,double Longitude){
        List<LatLng> latLngs = new ArrayList<LatLng>();
        latLngs.add(new LatLng(39.984864,116.305756));

         mTencentMap.addPolyline(new PolylineOptions().addAll(latLngs));

        polyline.appendPoints(listPoints );
        // 添加折线动画





    }
}
